package org.oxtypes.protobuf;

// OMG xTypes API

import org.omg.dds.type.dynamic.DynamicType;
import org.oxtypes.DynamicData;

// OxTypes implementation of xTypes API
import org.oxtypes.DynamicTypeFinder;
import org.oxtypes.DynamicDataFactory;

// Google's Protobuf external type and data representations
import com.google.protobuf.Descriptors.Descriptor;

public class WriteBuildApp {

    public static void main( String[] args ) {

        // load and register type (from some toolkit configuration file)

        DynamicTypeRegistry protoRegistry = DynamicTypeRegistry.getInstance();

        Descriptor d = Tbt.Position.getDescriptor();
        protoRegistry.registryDescriptor(d);

        // get type in the Position-specific producer or consumer applications
        // and prepare the id-based interface

        DynamicTypeFinder dtf = new DynamicTypeFinder();

        DynamicType dt = dtf.getType("Position");
        int xId  = dt.getMember("x").getId();
        int pxId = dt.getMember("px").getId();
        int yId  = dt.getMember("y").getId();

        // create and initialize producer's containers

        DynamicDataFactory prodFactory = DynamicDataFactory.getInstance();
        DynamicData prodData = prodFactory.createData(dt);

        double[] xs = {2.3, 2.4};

        prodData.setFloat64Values(xId, xs, 0, xs.length);
        prodData.setFloat64Value(pxId, 1.1);
        prodData.setFloat64Value(yId, 1.3);

        // serialize (and send data)

        DynamicDataWriter prodWriter = new DynamicDataWriter();

        int prodSize = prodWriter.computeByteSize(prodData);
        
        System.out.println("size: " + prodSize);

        byte bytes[] = new byte[prodSize];

        try {
            prodWriter.write(prodData, bytes);
        } catch (Exception e){
            e.printStackTrace();
            System.exit(1);
        }

        // (receive and)  deserialize data

        DynamicDataBuilder consBuilder = new DynamicDataBuilder();
        
        DynamicData consData = null;

        try {
           consData = consBuilder.build(dt, bytes);
        } catch (Exception e){
            e.printStackTrace();
            System.exit(1);
        }

        // print data

        DynamicData consX = consData.getComplexValue(xId);
        System.out.println("x  : length = " + consX.getLength());

        for(int i=0; i < consX.getLength(); i++){
            System.out.println(" " + i + " : " + consX.getFloat64Value(i));
        }

        System.out.println("px : " + consData.getFloat64Value(pxId));
        System.out.println("y  : " + consData.getFloat64Value(yId));
    }

}
